package org.example.rocketmq.a01_quickstart;

import org.apache.commons.lang3.ThreadUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.example.rocketmq.NamesrvAddr;

import java.time.Duration;
import java.time.LocalDateTime;

public class ProducerSync {
    public static void main(String[] args) throws Exception {
        syncProducer();
    }

    /**
     * 同步发送
     * 1. 可靠性要求高
     * 2. 数据量级较少
     * 3. 实时响应
     */
    public static void syncProducer() throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("producer_sync_group_01");
        producer.setNamesrvAddr(NamesrvAddr.get());
        producer.setSendMsgTimeout(15000); // 设置超时时间 15秒
        producer.start();

        for (int i = 0; i < 2; i++) {
            try {
                String body = (LocalDateTime.now() +  " Hello RocketMQ Sync" + i);
                System.out.println(body);
                Message message = new Message("TopicTest", "TagA", body.getBytes(RemotingHelper.DEFAULT_CHARSET));

                SendResult result = producer.send(message);
                // System.out.printf("%s%n", result);
            } catch (Exception e) {
                e.printStackTrace();
                ThreadUtils.sleep(Duration.ofSeconds(1));
            }
        }

        producer.shutdown();
    }
}
